﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ColorSelectorMVC.Models;

namespace ColorSelectorMVC.Helpers
{
    /// <summary>
    /// Custom validtor to ensure that the selected color is correct
    /// </summary>
    public class SettingsValidatorAttribute : ValidationAttribute
    {
        /// <summary>
        /// Ensures the the selected color is within the allowed selectable colors
        /// </summary>
        /// <param name="value">Settings model that is to be tested</param>
        /// <returns>Whether validation passed</returns>
        public override bool IsValid(object value)
        {
            var settingsModel = value as SettingsModel;
            if (settingsModel != null && settingsModel.SelectableColors != null)
            {
                var test = settingsModel.SelectableColors.Count(x => x.Value == settingsModel.SelectedColor);
                if (test > 0)
                {
                    return true;
                }
            }

            return false;
        }
    }

    /// <summary>
    /// Custom validtor to ensure that the selected color is correct
    /// </summary>
    public class ColorValidatorAttribute : ValidationAttribute, IClientValidatable
    {
        /// <summary>
        /// Ensures the the selected color is not null
        /// </summary>
        /// <param name="value">Selected color string</param>
        /// <returns>Whether validation passed</returns>
        public override bool IsValid(object value)
        {
            return value != null;
        }

        /// <summary>
        /// Client validation rules
        /// </summary>
        /// <param name="metadata"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationRule
            {
                ErrorMessage = ErrorMessage,
                ValidationType = "propercolor"
            };
        }
    }
}